<?php
/**
 * Created by PhpStorm.
 * User: yzr
 * Date: 1/28/2021
 * Time: 16:26
 */

/**
 * 任务接单相对应的操作
 */
namespace app\api\controller\wap;



use app\common\model\feature\communal\File;
use app\common\model\order\OrderTake;
use mall\utils\Tool;
use think\facade\Db;
use think\facade\Request;

class JobAccept extends Base
{


    /**
     * 我的接单列表
     */
    public function myList()
    {
        $where = [
            ['user_id','=',\mall\basic\Users::get('id')],
        ];
        switch(Request::get('type',0,'intval')) {
            case 1: //未提交
                $where[] = ['status','=',OrderTake::STATUS_ACCEPT];
                break;
            case 2: //待确认
                $where[] = ['status','=',OrderTake::STATUS_WAIT_CONFIRM];
                break;
            case 3: //未通过
                $where[] = ['status','=',OrderTake::STATUS_FAILED];
                break;
            case 4: //维权
                $where[] = ['status','=',OrderTake::STATUS_APPEAL];
                break;
            case 5: // 已通过（完成）
                $where[] = ['status','=',OrderTake::STATUS_FINISH];
                break;
            default:    //全部
                break;
        }
        return $this->fetchList($where);
    }

    /**
     * 通过JOB ID 获取列表
     * @param $jobId
     */
    public function fetchListByJobId($jobId){
        $outputFields = [
            'id'    => 'id',
            'users-nickname'  => 'users_name',
            'users-avatar'  => 'users_avatar',
            'create_time'   => 'create_time',
            'wait_expire'   => ['submit_expire_time'],
            'submit_time'   => 'submit_time',
            'status'    => 'status',
        ];
        return $this->fetchList([
            'job_id'    => $jobId
        ],$outputFields,['create_time'=>'DESC'])->getData();
    }


    /**
     * 我的接单详情
     * @param $id
     */
    public function myDetails($id){
        try{
            if(!$details = (new OrderTake())->findByIdAndJoinDetails($id,null,['job','job-publisher','job-requirement','job-images','images','users'])) {
                throw new \Exception('该接单任务不存在');
            }
            if(!in_array(\mall\basic\Users::get('id'),[$details['user_id'],$details['job-publisher_id']])) {
                throw new \Exception('该接单任务不存在');
            }
            $fields = [
                'id'    => 'id',
                'status'    => 'status',
                'failure_reason'    => 'failure_reason',
                'job-name' => 'name',
                'job-num' => 'num',
                'job-accept_num' => 'accept_num',
                'job-price'=> 'price',
                'job-total_amount'=> 'total_amount',
                'job-publisher-avatar'=>'job_avatar',
                'users-avatar'=>'accept_avatar',
                'job-task_link' => 'task_link',
                'job-requirement-requirement'   => 'requirement',
                'job-images'    => 'job_verify_imgs',
                'images'    => 'order_verify_imgs',
                ];

            $result = [];
            foreach($fields as $key=>$val) {
                if(is_integer($key)) {
                    $key = $val;
                }
                $echo = $details[$key];
                switch($key) {
                    case 'users-avatar':
                    case 'job-publisher-avatar':
                        $echo = Tool::url($echo,null,'avatar');
                        break;
                    case 'job-images':
                    case 'images':
                        $echo = array_map(function($filename) {
                            return [
                                'thumb_url'  => Tool::url($filename,null,'job'),
                                'url'   => Tool::url($filename),
                            ];
                        },$echo);
                        break;
                }
                $result[$val] = $echo;
            }

        } catch (\Exception $e) {
            return $this->returnAjax(Tool::getErrorMessage($e),0);
        }

        // 返回详情信息
        return $this->returnAjax("ok",1,$result);
    }


    /**
     * 提交任务
     * @param $id 任务ID
     * @return \think\response\Json
     */
    public function mySubmit($id) {
        try{
            if(!$details = (new OrderTake())->findByIdAndJoinDetails($id,\mall\basic\Users::get('id'))) {
                throw new \Exception('该接单任务不存在');
            }
            if(!OrderTake::isAccept($details['status'])) {
                throw new \Exception('非未提交状态不能提交');
            }

            if(Request::get('upload')) {    // 上传图片
                return $this->submitUpload();
            }

            /******************* 任务提交 *******************/
            // 验证并获取图片
            $params = $this->mySubmitValidateParams();
            Db::startTrans();
            //提交任务
            (new OrderTake())->submit($details,$params);
            Db::commit();
            /***************** END 任务提交 *****************/
        } catch (\Exception $e) {
            Db::rollback();
            return $this->returnAjax(Tool::getErrorMessage($e),0);
        }

        // 返回详情信息
        return $this->returnAjax("接单任务提交成功",1,[]);
    }

    /**
     * 验证不通过
     * @param $id 任务ID
     * @return \think\response\Json
     */
    public function statusFail($id) {
        try{
            if(!($details = (new OrderTake())->findByIdAndJoinDetails($id,null,['job'])) || $details['job-publisher_id'] != \mall\basic\Users::get('id')) {
                throw new \Exception('该接单任务不存在');
            }

            if(!OrderTake::isWaitConfirm($details['status'])) {
                throw new \Exception('非提交状态不能进行验证');
            }

            /******************* 验证失败 *******************/
            // 验证并获取原因
            $params = array_map(function($value){return trim($value);},Request::post());
            validate([
                'failure_reason'  => 'require|min:2|max:250',
            ],[
                'failure_reason'   =>  '失败原因必须 2 ~ 250 个字',
            ])->check($params);
            Db::startTrans();
            //提交任务
            (new OrderTake())->failed($details,$params);
            Db::commit();
            /***************** END 验证失败 *****************/
        } catch (\Exception $e) {
            Db::rollback();
            return $this->returnAjax(Tool::getErrorMessage($e),0);
        }

        // 返回详情信息
        return $this->returnAjax("验证失败成功",1,[]);
    }


    /**
     * 维权
     * @param $id 任务ID
     * @return \think\response\Json
     */
    public function statusAppeal($id) {
        try{
            if(!$details = (new OrderTake())->findByIdAndJoinDetails($id,\mall\basic\Users::get('id'),['job'])) {
                throw new \Exception('该接单任务不存在');
            }

            if(!OrderTake::isFailed($details['status'])) {
                throw new \Exception('非失败状态不能申请维权');
            }
            if($details['is_closed']) {
                throw new \Exception('订单已过维权期间而结束，不能申请维权');
            }
            /******************* 维权 *******************/
            Db::startTrans();
            //提交任务
            (new OrderTake())->appeal($details);
            Db::commit();
            /***************** END 维权 *****************/
        } catch (\Exception $e) {
            Db::rollback();
            return $this->returnAjax(Tool::getErrorMessage($e),0);
        }

        // 返回详情信息
        return $this->returnAjax("申请维权成功，请等待审核结果",1,[]);
    }

    /**
     * 验证成功
     * @param $id
     */
    public function statusSuccess($id) {
        try{
            if(!($details = (new OrderTake())->findByIdAndJoinDetails($id,null,['job'])) || $details['job-publisher_id'] != \mall\basic\Users::get('id')) {
                throw new \Exception('该接单任务不存在');
            }

            if(!OrderTake::isWaitConfirm($details['status'])) {
                throw new \Exception('非提交状态不能进行验证');
            }

            /******************* 验证成功 *******************/
            Db::startTrans();
            //提交任务
            (new OrderTake())->success($details);
            Db::commit();
            /***************** END 验证成功 *****************/
        } catch (\Exception $e) {
            Db::rollback();
            return $this->returnAjax(Tool::getErrorMessage($e),0);
        }

        // 返回详情信息
        return $this->returnAjax("确认完成成功",1,[]);
    }



    /**
     * 提交前验证参数
     */
    private function mySubmitValidateParams(){
        $returnErrFunc = function ($errMsg) {
            throw new \Exception($errMsg);
        };
        $params = array_map(function($value){return trim($value);},Request::post());
        validate([
            'verify_imgs'   => 'require',
        ],[
            'verify_imgs'   => '请选择图片',
        ])->check($params);


        /**** 验证图片 ******/
        $params['verify_imgs'] = array_unique(explode(',',$params['verify_imgs']));
        $num = count($params['verify_imgs']);
        if($num <1 || $num >3) {
            $returnErrFunc('提交图片必须 1 ~ 3 张');
        }
        foreach($params['verify_imgs'] as $filename) {
            if( $this->getFileType() != OrderTake::FILE_TYPE || !File::file_exists($filename,$this->getFileType())) {
                $returnErrFunc('图片不存在，请重试');
            }
        }
        /** END 验证图片 ****/
        return $params;
    }



    /**
     * 统一接单列表输出
     */
    private function fetchList($where,$outputFields = null,$order = null)
    {
        try {
            $outputFields = empty($outputFields)?[
                'id'    => 'id',
                'job-name'  => 'job_name',
                'job-price'  => 'price',
                'job_users-avatar'  => 'job_avatar',
                'create_time'   => 'create_time',
                'wait_expire'   => ['submit_expire_time'],
                'submit_time'   => 'submit_time',
                'status'    => 'status',
            ]:$outputFields;
            $order = empty($order)?['create_time'=>'DESC']:$order;

            $tmp = [];
            foreach ($outputFields as $key=>$val) {
                $tmp[is_integer($key)?$val:$key] = $val;
            }
            $outputFields = $tmp;
            // 获取任务列表
            $list = (new OrderTake())->recordAllPageByDropDown($where,10,$order,array_keys($outputFields));
            $list['list'] = array_map(function ($value) use($outputFields){
                $return = [];
                foreach($outputFields as $key=>$val) {
                    $data = $value[$key];
                    switch($key) {
                        case 'job-price':
                            $data -= 0;
                            break;
                        case 'users-avatar':    // 头像处理
                        case 'job_users-avatar':    // 头像处理
                            break;
                        case 'wait_expire':
                        case 'submit_exp_time': //  处理日期
                        case 'submit_time':
                        case 'create_time':
                            $data = $data == 0?'-':date('Y/m/d H:i',$data);
                            break;
                    }
                    if(is_array($val)) {
                        foreach($val as $val_key) {
                            $tmp = $data;
                            switch($val_key) {
                                case 'submit_exp_time':
                                    $tmp = array_key_exists('status',$value) || OrderTake::isAccept($value['status'])?$data:'-';
                                    break;
                            }
                            $return[$val_key] = $tmp;
                        }
                    } else {
                        $return[$val] = $data;
                    }

                }
                return $return;
            },$list['list']);
        }catch (\Exception $e) {
            return $this->returnAjax(Tool::getErrorMessage($e),0);
        }

        // 返回列表信息
        return $this->returnAjax("ok",1,$list);
    }


    /**
     * 上传文件
     * @return \think\response\Json
     */
    private function submitUpload(){
        try{
            $resultData = File::upload($this->getFileType(),'file');
        }catch (\Exception $e) {
            return $this->returnAjax(Tool::getErrorMessage($e),0);
        }
        return $this->returnAjax("ok",1,$resultData);
    }


    /**
     * 获取存储文件的文件类型
     * @return string
     */
    private function getFileType()
    {
        return OrderTake::FILE_TYPE;
    }


}
